package com.wgke.bluetooth.utils;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.os.ParcelUuid;
import android.text.TextUtils;
import android.util.Log;

import com.wgke.bluetooth.event.EventBean;
import com.wgke.bluetooth.event.EventGattBean;
import com.wgke.bluetooth.event.EventReadBean;
import com.wgke.bluetooth.event.EventWriteBean;
import com.wgke.bluetooth.tools.GattServiceBean;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

public class BluetoothGattManager {
    private static BluetoothGattManager manager;

    private BluetoothDevice device;
    private List<BluetoothGattService> services;
    private BluetoothGatt bluetoothGatt;


    public static BluetoothGattManager getInstance() {
        if (manager == null) {
            manager = new BluetoothGattManager();
        }
        return manager;
    }

    public BluetoothDevice getDevice() {
        return device;
    }

    public List<BluetoothGattService> getServices() {
        return services;
    }

    public BluetoothGattService getService(String uuid) {
        for (BluetoothGattService service : services) {
            if (TextUtils.equals(service.getUuid().toString(), uuid)) {
                return service;
            }
        }
        return null;
    }

    public BluetoothGatt getGatt() {
        return bluetoothGatt;
    }

    public String getServiceName(UUID uuid) {
        return BluetoothServiceNameResolver.getServiceName(uuid);
    }

    public String getCharacteristicName(UUID uuid) {
        return BluetoothServiceNameResolver.getCharacteristicName(uuid);
    }

    @SuppressLint("MissingPermission")
    public void connectDevice(BluetoothDevice device) {
        this.device = device;
        this.bluetoothGatt = null;
        this.services = null;
        Log.e("BluetoothGattManager", "connectDevice: " + device.getName() + "----start---");
        device.connectGatt(CommonUtil.getContext(), false, gattCallback);
    }

    @SuppressLint("MissingPermission")
    public void close() {
        if (bluetoothGatt != null) {
            Log.e("BluetoothGattManager", "close: " + "----start---");
            bluetoothGatt.disconnect();
            this.bluetoothGatt.close();
            this.services = null;
        }
    }

    public static String getPropertyDescription(int properties) {
        return BluetoothServiceNameResolver.getPropertyDescription(properties);
    }

    public List<GattServiceBean> handleData(List<BluetoothGattService> services) {
        List<GattServiceBean> list = new ArrayList<>();
        Log.e("BluetoothGattManager", "services size ：" + services.size());
        for (BluetoothGattService service : services) {
            GattServiceBean bean = new GattServiceBean();
            bean.list = new ArrayList<>();
            // 获取服务UUID
            bean.uuid = service.getUuid();
            Log.e("BluetoothGattManager", "service UUID：" + bean.uuid);
            // 获取服务的所有特征
            List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
            for (BluetoothGattCharacteristic characteristic : characteristics) {
                GattServiceBean.GattCharacteristicBean b = new GattServiceBean.GattCharacteristicBean();
                // 获取特征UUID
                b.uuid = characteristic.getUuid();

                Log.e("BluetoothGattManager", "character UUID：" + b.uuid);
                // 获取特征的属性（读/写/通知等）
                b.properties = characteristic.getProperties();
                bean.list.add(b);
                if ((b.properties & BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
                    // 可读特征
                }
                if ((b.properties & BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {
                    // 可写特征
                }
                if ((b.properties & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                    // 可通知特征
                    // 启用通知
//                    gatt.setCharacteristicNotification(characteristic, true);
//
//                    // 获取描述符并启用通知
//                    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
//                    if (descriptor != null) {
//                        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
//                        gatt.writeDescriptor(descriptor);
//                    }
                }
            }
            list.add(bean);
        }
        return list;
    }

    public final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        @SuppressLint("MissingPermission")
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                EventBus.getDefault().post(new EventBean(1, gatt.getDevice()));
                gatt.discoverServices(); // 发现服务
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                // 处理断开连接
                EventBus.getDefault().post(new EventBean(2, gatt.getDevice()));
                gatt.close();
            } else {
                EventBus.getDefault().post(new EventBean(0, gatt.getDevice()));
            }
        }

        @SuppressLint("MissingPermission")
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                bluetoothGatt = gatt;
                services = gatt.getServices();
                EventBus.getDefault().post(new EventGattBean(1));
            } else {
                EventBus.getDefault().post(new EventGattBean(0));
            }
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            // 处理特征读取结果
            if (status == BluetoothGatt.GATT_SUCCESS) {
                byte[] data = characteristic.getValue();
                EventBus.getDefault().post(new EventReadBean(true, data));
                // 处理读取到的数据
                Log.w("BluetoothGattManager", "bleRead：" + Arrays.toString(data));
            }
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                EventBus.getDefault().post(new EventWriteBean(true));
            } else {
                EventBus.getDefault().post(new EventWriteBean(false, "errorStatus:" + status));
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            // 处理特征值变化（通知）
            byte[] data = characteristic.getValue();
            // 处理通知数据
            // 处理读取到的数据
            Log.w("onCharacteristicChanged", "bleNotify:" + Arrays.toString(data));
            if (SpUtil.getUsePolicy()) {
                getProcessor().process(data);
            } else {
                processor = null;
                LogUtil.saveLog("receive packet", data);
                EventBus.getDefault().post(new EventReadBean(false, data));
            }
        }
    };

    /**
     * 将 byte[] 中的每个元素当作无符号 byte 处理（0-255），
     * 进行运算后仍返回 byte[]
     *
     * @param input 输入 byte 数组
     * @return 处理后的 byte 数组
     */
    public static byte[] processAsUnsigned(byte[] input) {
        if (input == null) return null;
        byte[] output = new byte[input.length];
        for (int i = 0; i < input.length; i++) {
            // 将 byte 当作无符号处理（0-255）
            int unsignedValue = input[i] & 0xFF;
            // 在这里可以进行无符号运算
            // 例如：unsignedValue = unsignedValue * 2;
            // 将结果转回 byte（会截断高位，保留低8位）
            output[i] = (byte) (unsignedValue & 0xFF);
        }

        return output;
    }

    private ConfigurableByteArrayProcessor getProcessor() {
        if (processor == null) {
            byte[] header = SpUtil.getUsePolicyHeader();
            processor = new ConfigurableByteArrayProcessor.Builder().setHeader(header[0], header[1])  // 可选，默认就是0x5A,0xA5
                    .setFooter(SpUtil.getUsePolicyFooter())              // 可选，默认就是0xAA
                    .setUseLengthField(SpUtil.getUsePolicySize())           // 禁用长度字段
                    .setUseChecksum(SpUtil.getUsePolicySum())              // 禁用校验和
                    .build(packet -> {
                        LogUtil.saveLog("receive packet", packet);
                        EventBus.getDefault().post(new EventReadBean(false, packet));
                    });
        }
        return processor;
    }
    // 创建处理器并设置监听器
    // ByteArrayProcessor processor = new ByteArrayProcessor(packet -> EventBus.getDefault().post(new EventReadBean(packet)));

    // 创建处理器（使用Builder模式配置）
    ConfigurableByteArrayProcessor processor = null;


}
